package com.easyskool.services.core;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.easyskool.composer.IdentityModuleComposer;
import com.easyskool.composer.UserServiceComposer;
import com.easyskool.constants.CommonConstants;
import com.easyskool.constants.MessageConstants;
import com.easyskool.hibernate.model.AccessGroupMapper;
import com.easyskool.hibernate.model.AccessGroups;
import com.easyskool.hibernate.model.ContactForms;
import com.easyskool.hibernate.model.Schools;
import com.easyskool.hibernate.model.UserAuthorization;
import com.easyskool.hibernate.model.UserProfiles;
import com.easyskool.util.mailUtil;
//import com.easyskool.hibernate.model.AccessAuthorization;
import com.easyskool.utilfunction.UtilFunctions;
import com.ivp.cloud.stratus.logger.LoggingUtil;
import com.sun.jersey.spi.container.servlet.PerSession;

@Path("/idModService")
@PerSession
public class IdentityModuleService implements Serializable {

	IdentityModuleComposer idService = new IdentityModuleComposer();
	private static LoggingUtil logger = (LoggingUtil) LoggingUtil
			.getLogger(IdentityModuleService.class.getName());

	@Path("/getDefaultGroups")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response getDefaultGroups(@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		logger.info(" Getting default groups for the user ");
		String userAccessGroup = (String) session
				.getAttribute(CommonConstants.ACCESS_GROUPS);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		logger.info("School code is "+ school.getSchoolCode());
		List<AccessGroups> ags=new ArrayList<AccessGroups>();
		try {
			ags = idService.getDefaultGroups(userAccessGroup,school);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (ags.size() == 0 || ags == null) {
			logger.error("No default Access Group Found for User ");
			return UtilFunctions.createErrorResponse(404,
					CommonConstants.OPERATION,
					MessageConstants.ERROR_MESSAGE_DATA_NOT_LOADED);
		}
		System.out.println(ags.get(0).getAgCode() + " FIRST GROUP");
		JSONArray jsonArray = new JSONArray();
		try {
			// Only default accessGroups are returned no matter what
			for (int i = 0; i < ags.size(); i++) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("agCode", ags.get(i).getAgCode());
				jsonObject.put("agName", ags.get(i).getAgName());
				jsonObject.put("agDesc", ags.get(i).getAaDescription());
				jsonArray.put(jsonObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("Default Group JSON " + jsonArray);
		return UtilFunctions.createObjectResponse(200, jsonArray.toString());

	}
	
	@Path("/getUsers")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response getUsers(@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		String userAccessGroup = (String) session
				.getAttribute(CommonConstants.ACCESS_GROUPS);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		logger.info("Getting users for School code: "+ school.getSchoolCode()+" USER: "+user);
		List<UserAuthorization> ags = idService.getUsers(user,school,userAccessGroup);

		 
		JSONArray jsonArray = new JSONArray();
		try {
			if(ags!=null)
			for (int i = 0; i < ags.size(); i++) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("uaName", ags.get(i).getUaName());
				jsonObject.put("uaEmail", ags.get(i).getUaEmail());
				jsonObject.put("uaMobile", ags.get(i).getUaMobileNumber());
				jsonObject.put("uaMaker", ags.get(i).getCreatedBy());
				jsonObject.put("uaCode", ags.get(i).getUaCode());
				jsonObject.put("uaGroup", ags.get(i).getAccessGroups().getAgName());
				jsonArray.put(jsonObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("Default Group JSON " + jsonArray);
		return UtilFunctions.createObjectResponse(200, jsonArray.toString());

	}
	
	@Path("/saveCustomGroup")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response saveCustomGroup(String jsonData,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		logger.info(" Saving custom groups for the user "+jsonData);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		JSONObject json = new JSONObject(jsonData);
		System.out.println(json.keys().toString());
		Iterator<?> keys = json.keys();
		ArrayList<String> groups =new ArrayList<String>();
		 while( keys.hasNext() ){
	            String key = (String)keys.next();
	            System.out.println(key);
	            if(key.contains("groups"))
	            {
	            	groups.add(json.getString(key));
	            }
	        }
		int NoRecords= idService.saveCustomGroup(user,json.getString("description"),json.getString("groupName"),groups,school);
		if(NoRecords==1)
			return UtilFunctions.createSuccessResponse(200,CommonConstants.SUCCESS, CommonConstants.RECORD_SAVED_SUCCESSFULLY);
		else
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
	}
	@Path("/insertUser")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response insertUser(String jsonData,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		logger.info(" Saving custom groups for the user "+jsonData+" "+user);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		JSONObject json = new JSONObject(jsonData);
		System.out.println(json.keys().toString());
		int NoRecords= idService.insertUser(user,json.getString("email"),json.getString("customGroups"),school);
		if(NoRecords==1)
			return UtilFunctions.createSuccessResponse(200,CommonConstants.SUCCESS, CommonConstants.RECORD_SAVED_SUCCESSFULLY);
		else
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
	}
	@Path("/updateUser")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response updateUser(String jsonData,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		logger.info(" Saving custom groups for the user "+jsonData+" "+user);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		JSONObject json = new JSONObject(jsonData);
		System.out.println(json.keys().toString());
		int NoRecords=0;
		try {
			NoRecords = idService.updateUser(user,json.getString("uGroupCode"),json.getString("ucode"));
		} catch (Exception e) {
			e.printStackTrace();
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
		}
		if(NoRecords==1)
			return UtilFunctions.createSuccessResponse(200,CommonConstants.SUCCESS, CommonConstants.RECORD_SAVED_SUCCESSFULLY);
		else
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
	}

	@Path("/deleteUser")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response deleteUser(String jsonData,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		logger.info(" Saving custom groups for the user "+jsonData+" "+user);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		JSONObject json = new JSONObject(jsonData);
		System.out.println(json.keys().toString());
		int NoRecords=0;
		try {
			NoRecords = idService.deleteUser( user,json.getString("uCode"));
		} catch (Exception e) {
			e.printStackTrace();
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
		}
		if(NoRecords==1)
			return UtilFunctions.createSuccessResponse(200,CommonConstants.SUCCESS, CommonConstants.RECORD_REMOVED_SUCCESSFULLY);
		else
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
	}
	@Path("/deleteMultipleUser")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response deleteMultipleUser(String jsonData,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		logger.info(" Deleting users with ids "+jsonData+" "+user);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		JSONObject json = new JSONObject(jsonData);
		System.out.println(json.keys().toString());
		int NoRecords=0;
		String idString=json.getString("uCode");
		String ids[]=idString.split(",");
		int flag=0;
		String notDeletedIds="";
		try {
			for(int i=1;i<ids.length;i++)
			{
				if("".equals(ids[i]))
					continue;
				if(ids[i]!=null||!"".equals(ids[i]))
				{NoRecords = idService.deleteUser( user,ids[i]);
				if(NoRecords!=1)
				{		
					flag=1;
					notDeletedIds	=notDeletedIds	+","+ids[i];
				}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR_, CommonConstants.ERROR_STORING_RECORD);
		}
		if(flag==0)
			return UtilFunctions.createSuccessResponse(200,CommonConstants.SUCCESS, CommonConstants.RECORD_REMOVED_SUCCESSFULLY);
		else
			return UtilFunctions.createSuccessResponse(200,CommonConstants.ERROR_, notDeletedIds);
	}
	@Path("/deleteCustomGroup")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response deleteCustomGroup(String jsonData,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		logger.info(" Saving custom groups for the user "+jsonData);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		JSONObject json = new JSONObject(jsonData);
		logger.info(" Deleting custom groups for the user "+ user+" "+school.getSchoolName()+jsonData);
		int NoRecords=0;;
		try {
			NoRecords = idService.deleteCustomGroup(user,json.getString("agCode") ,school);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(NoRecords==1)
			return UtilFunctions.createSuccessResponse(200,CommonConstants.SUCCESS, CommonConstants.RECORD_SAVED_SUCCESSFULLY);
		else
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
	}
	
	@Path("/updateCustomGroup")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response updateCustomGroup(String jsonData,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		logger.info(" Saving custom groups for the user "+jsonData);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		JSONObject json = new JSONObject(jsonData);
		System.out.println(json.keys().toString());
		Iterator<?> keys = json.keys();
		HashMap<String,Integer> newgroups =new HashMap<String,Integer>();
		 while( keys.hasNext() ){
	            String key = (String)keys.next();
	            System.out.println(key);
	            if(key.contains("groupNames"))
	            {
	            	newgroups.put(json.getString(key),1);
	            }
	        }
		int NoRecords=0;;
		try {
			NoRecords = idService.updateCustomGroup(user,json.getString("udescription"),json.getString("ucode"),newgroups,school);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(NoRecords==1)
			return UtilFunctions.createSuccessResponse(200,CommonConstants.SUCCESS, CommonConstants.RECORD_SAVED_SUCCESSFULLY);
		else
			return UtilFunctions.createSuccessResponse(500,CommonConstants.ERROR, CommonConstants.ERROR_STORING_RECORD);
	}
	@Path("/getCustomGroups")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response getCustomGroups(@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		logger.info(" Getting default groups for the user ");
		String userAccessGroup = (String) session
				.getAttribute(CommonConstants.ACCESS_GROUPS);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		
		logger.info("School code is "+ school.getSchoolCode());
		List<AccessGroups> ags=new ArrayList<AccessGroups>();
		try {
			ags = idService.getCustomGroups(user,userAccessGroup,school);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (ags.size() == 0 || ags == null) {
			logger.error("No Custom Access Group Found for User ");
			return UtilFunctions.createErrorResponse(404,
					CommonConstants.OPERATION,
					MessageConstants.ERROR_MESSAGE_DATA_NOT_LOADED);
		}
		System.out.println(ags.get(0).getAgCode() + " FIRST GROUP");
		JSONArray jsonArray = new JSONArray();
		try {
			// Only default accessGroups are returned no matter what
			for (int i = 0; i < ags.size(); i++) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("agCode", ags.get(i).getAgCode());
				jsonObject.put("agName", ags.get(i).getAgName());
				jsonObject.put("agDesc", ags.get(i).getAaDescription());
				jsonArray.put(jsonObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("Default Group JSON " + jsonArray);
		return UtilFunctions.createObjectResponse(200, jsonArray.toString());

	}
	
	
	@Path("/getCustomGroup")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response getCustomGroup(String code,@Context HttpServletRequest req)
			throws JSONException {
		HttpSession session = req.getSession(true);
		logger.info(" Getting default groups for the user ");
		String userAccessGroup = (String) session
				.getAttribute(CommonConstants.ACCESS_GROUPS);
		Schools school = (Schools) session
				.getAttribute(CommonConstants.SCHOOL_CODE);
		String user = (String) session
				.getAttribute(CommonConstants.USERCODE);
		JSONObject j=new JSONObject(code);
		logger.info("School code is "+ school.getSchoolCode());
		List<AccessGroupMapper> ags = idService.getCustomGroup(user,j.getString("agCode"));

		
		if (ags.size() == 0 || ags == null) {
			logger.error("No Custom Access Group Found for User ");
			return UtilFunctions.createErrorResponse(200,
					CommonConstants.OPERATION,
					MessageConstants.ERROR_MESSAGE_DATA_NOT_LOADED);
		}
		JSONArray jsonArray = new JSONArray();
		try {
			// Only default accessGroups are returned no matter what
			for (int i = 0; i < ags.size(); i++) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("agCode", ags.get(i).getAccessGroupsByAgmDefaultGroupCode().getAgCode());
				jsonObject.put("agDesc", ags.get(i).getAccessGroupsByAgmDefaultGroupCode().getAaDescription());
				jsonArray.put(jsonObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("Default Group JSON " + jsonArray);
		return UtilFunctions.createObjectResponse(200, jsonArray.toString());

	}
	
}